package com.tiancai.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tiancai.context.BaseContext;
import com.tiancai.mapper.UserMapper;
import com.tiancai.mapper.WorkMapper;
import com.tiancai.pojo.po.Collect;
import com.tiancai.mapper.CollectMapper;
import com.tiancai.pojo.po.User;
import com.tiancai.pojo.po.Work;
import com.tiancai.service.ICollectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tiancai
 * @since 2025-03-17
 */
@Service
public class CollectServiceImpl extends ServiceImpl<CollectMapper, Collect> implements ICollectService {


    @Autowired
    private CollectMapper collectMapper;

    @Autowired
    private WorkMapper workMapper;

    @Autowired
    private UserMapper userMapper;
    @Override
    public Collect addCollect(Long workId) {
        //在收藏表里查找是否收藏了
        QueryWrapper<Collect> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Collect::getUserId, BaseContext.getCurrentId()).eq(Collect::getWorkId, workId);
        if (collectMapper.selectOne(wrapper) != null) {
            //如果查到了则删除
            collectMapper.delete(wrapper);
            Work work = workMapper.selectById(workId);
            work.setCollectCount(work.getCollectCount()-1);
            workMapper.updateById(work);

            //作品的作者
            User user = userMapper.selectById(work.getUserId());
            user.setCollectCount(user.getOwnCollectCount()-1);
            userMapper.updateById(user);

            //收藏作品的用户
            User user1 = userMapper.selectById(BaseContext.getCurrentId());
            user1.setOwnCollectCount(user1.getCollectCount()-1);
            userMapper.updateById(user1);
            return null;
        }else {
            //如果没有则添加
            Collect collect = Collect.builder()
                    .workId(workId)
                    .userId(BaseContext.getCurrentId())
                    .build();
            collectMapper.insert(collect);
            Work work = workMapper.selectById(workId);
            work.setCollectCount(work.getCollectCount()+1);
            workMapper.updateById(work);

            //作品的作者
            User user = userMapper.selectById(work.getUserId());
            user.setCollectCount(user.getOwnCollectCount()+1);
            userMapper.updateById(user);
            //收藏作品的用户
            User user1 = userMapper.selectById(BaseContext.getCurrentId());
            user1.setOwnCollectCount(user1.getCollectCount()+1);
            userMapper.updateById(user1);
            return collect;
        }

    }
}
